package unimelb.discussiontracker.twitter.service.integration;

import java.util.Date;

import org.apache.log4j.Logger;

import unimelb.discussiontracker.twitter.data.dao.IIntervalDao;
import unimelb.discussiontracker.twitter.data.dao.ITopicIntervalAssociationDao;
import unimelb.discussiontracker.twitter.data.entity.IntervalEntity;
import unimelb.discussiontracker.twitter.data.entity.TopicEntity;
import unimelb.discussiontracker.twitter.data.entity.TopicIntervalAssociation;

public class TopicIntervalParser extends AbstractFileProcessor {

    private static final Logger logger = Logger.getLogger(TopicIntervalParser.class);

    private IIntervalDao intervalDao;

    private ITopicIntervalAssociationDao topicIntervalAssocDao;

    public void setIntervalDao(IIntervalDao intervalDao) {
        this.intervalDao = intervalDao;
    }

    public void setTopicIntervalAssocDao(ITopicIntervalAssociationDao topicIntervalAssocDao) {
        this.topicIntervalAssocDao = topicIntervalAssocDao;
    }

    @Override
    protected void processLine(String line, TopicEntity masterTopic) {
        try {
            final String[] tokens = line.trim().split(" ", 4);

            if (tokens.length != 4) {
                logger.error("Invalid line:" + line);
                return;
            }

            final Date startDate = dateFormat.parse(tokens[0].trim());
            final Date endDate = dateFormat.parse(tokens[1].trim());
            final int sentiment = Integer.parseInt(tokens[2].trim());
            final String topicText = tokens[3].trim();

            if (!topicText.equals(masterTopic.getText())) {
                logger.error("Invalid topic:" + topicText);
                return;
            }

            IntervalEntity interval = intervalDao.findByStartEnd(startDate, endDate);
            if (interval == null) {
                interval = new IntervalEntity();
                interval.setStart(startDate);
                interval.setEnd(endDate);

                intervalDao.save(interval);
            }

            TopicIntervalAssociation assoc = topicIntervalAssocDao.findByTopicIdAndIntervalId(masterTopic.getId(), interval.getId());
            if (assoc == null) {
                assoc = new TopicIntervalAssociation();
                assoc.setInterval(interval);
                assoc.setTopic(masterTopic);
                assoc.setSentiment(sentiment);

                topicIntervalAssocDao.save(assoc);
            } else {
                assoc.setSentiment(sentiment);

                topicIntervalAssocDao.update(assoc);
            }
        } catch (Exception e) {
            logger.error("Invalid line: " + line, e);
        }

    }

}
